# -*- coding: utf-8 -*-
# created on 2016/03/30

from sympy import sympify, simplify, solveset, S
from mathsolver.functions.base import BaseFunction, BaseEq, BaseVariable, BaseSymbolValue, new_latex
from mathsolver.functions.daoshu.daoshuyunsuan import HanShuDaoShuYunSuan
from mathsolver.functions.hanshu.helper import cal_canshu_from_expr, process_m_eqsolver_output, check_func
from mathsolver.functions.mathematica.mathematicaSolve import MathematicaSolve


class JiZhiDianGuanXiQiuCan(BaseFunction):
    def solver(self, *args):
        if len(args) == 3:
            func, eq, ineq_pf = check_func(args[0]), args[1], args[2]
        else:
            func, eq = check_func(args[0]), args[1]

        expr, var = func.expression, func.var

        # 计算函数极值点
        deriv_func = HanShuDaoShuYunSuan().solver(func).output[0]
        self.steps.append(["", "对函数求导得 %s" % deriv_func.printing()])

        canshu_symbol = cal_canshu_from_expr(expr)
        canshu_interval = self.search(canshu_symbol)

        if canshu_interval:
            m_solver = MathematicaSolve().solver(BaseEq([deriv_func.expression, 0]), BaseVariable([deriv_func.var]),
                                                 {canshu_symbol: canshu_interval})
        else:
            m_solver = MathematicaSolve().solver(BaseEq([deriv_func.expression, 0]), BaseVariable([var]))

        # 处理 Mathematica 的输出
        m_solver_result = process_m_eqsolver_output(m_solver.output[0].value, var)
        #  {x: {-a/6 - sqrt(a**2 + 4)/6 - 1/3, -a/6 + sqrt(a**2 + 4)/6 - 1/3}}
        for k, v in m_solver_result.items():
            if isinstance(k, tuple):
                assert len(v) == 1
                solver_dict = dict(zip(k, v[0]))
                var_solution = solver_dict[var]
                canshu_solution = solver_dict[canshu_symbol]
            else:
                var_solution = v

        self.steps.append(["", "令导数等于零，得到函数在 %s = %s 处取到极值点"
                           % (new_latex(func.var), " 或者 ".join(new_latex(solu) for solu in var_solution))])

        # 处理给定的等式 Abs(x_1 - x_2) = 2
        eq_left, eq_right = sympify(eq.value)
        eq_expr = eq_left - eq_right
        eq_symbols = eq_expr.free_symbols

        # 将极值代入等式，得到：Abs(sqrt(4*a + b**2/a**2)) - 2
        eq_expr_new = simplify(eq_expr.subs(dict(zip(eq_symbols, var_solution))))
        self.steps.append(["", "将极值点代入 %s = 0 得到：%s = 0" % (new_latex(eq_expr), new_latex(eq_expr_new))])

        if len(args) == 3:
            self.steps.append(["", "给定条件 %s = 0 和 %s ∈ %s，求 %s 的最大值和最小值得到：%s" % (
                new_latex(eq_expr_new), new_latex(canshu_symbol), new_latex(canshu_solution), new_latex(canshu_symbol), ineq_pf.printing())])
            self.steps.append(["", "得证"])
        else:
            result = solveset(eq_expr_new, domain=S.Reals)
            result_output = BaseSymbolValue({cal_canshu_from_expr(expr): result})
            self.steps.append(["", "解得：%s" % result_output.printing()])
        return self


if __name__ == '__main__':
    pass
